﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ZSZ.CommonMVC;
using ZSZ.DTO;
using ZSZ.IService;
using ZSZ.Model;
using ZSZ.Website.Areas.WebAdmin.Filters;

namespace ZSZ.Website.Areas.WebAdmin.Controllers
{
    [AdminAuthorize(IsCheck = true)]
    public class CityController : Controller
    {
        public ICityService cityService { get; set; }
        // GET: WebAdmin/City
        [AdminAuthorize(IsCheck = false)]
        public ActionResult List(int pageIndex = 1)
        {
            long total;
            int pageSize = 10, maxPagerCount = 10;
            List<City> list = cityService.GetPagedData(out total, pageIndex, pageSize).ToList();
            ViewBag.totalCount = total;
            ViewBag.pageIndex = pageIndex;
            ViewBag.pageSize = pageSize;
            ViewBag.maxPagerCount = maxPagerCount;
            return View(list);
        }

        [HttpGet]
        public ActionResult Add()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Add(string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "城市名称不能为空" });
            }
            cityService.Add(name);
            return Json(new AjaxResult { Status = "ok" });
        }

        [HttpGet]
        public ActionResult Edit(long id)
        {
            CityDTO model = cityService.GetDTOById(id);
            if (model == null)
            {
                return View("Error", (object)"获取不到城市信息");
            }
            return View(model);
        }

        [HttpPost]
        public ActionResult Edit(long id, string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "城市名称不能为空" });
            }
            City model = cityService.GetById(id);
            if (model == null)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "城市信息不存在" });
            }
            cityService.Update(id,name);
            return Json(new AjaxResult { Status = "ok" });
        }


        [HttpPost]
        public ActionResult Delete(long id)
        {
            CityDTO model = cityService.GetDTOById(id);
            if (model == null)
            {
                return View("Error", (object)"获取不到城市信息");
            }
            cityService.MarkDeleted(id);
            return Json(new AjaxResult { Status = "ok" });
        }

        [HttpPost]
        public ActionResult BatchDelete(long[] selectdIds)
        {
            List<long> list = new List<long>();
            foreach (long id in selectdIds)
            {
                list.Add(id);
            }
            cityService.BatchMarkDeleted(list);
            return Json(new AjaxResult { Status = "ok" });
        }
    }
}